﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.ComponentModel;
using AlexandriaPressUserBusinessLayer;
using AlexandriaPressUserObject;
using AlexandriaPressPublisherBusinessLayer;

namespace AlexandriaPressWebsite.MasterPages
{
    public partial class WebForm17 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["blocked"] != null)
            {
                Session.RemoveAll();
                Response.Redirect("~/MasterPages/MainPage.aspx");
            }
        }

        protected void downloadButton_Click(object sender, EventArgs e)
        {
            string placeHolder = "";
            string destinationUrl = "";
            List<OrderItems> order = (List<OrderItems>)Session["orders"];   

            try
            {
                foreach (OrderItems book in order)
                {
                    for (int aemeth = 0; aemeth < book.Quantity; aemeth++)
                    {
                        WebClient client = new WebClient();

                        client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                        if (aemeth == 0)
                        {
                            placeHolder = ".";
                        }
                        else
                        {
                            placeHolder = Convert.ToString(aemeth) + ".";                        
                        }

                        client.DownloadFileAsync(new Uri(UserBusinsessLayer.getFileLocation(book.BookID, ref destinationUrl)), destinationUrl.Replace(".", placeHolder));
                    }
                }
                Session.Remove("orders");
                Session.Remove("newOrders");
                Session.Remove("tempOrder");
                Session.Remove("numItems");
            }
            catch (Exception ex)
            {
                downloadMessageLabel.Text = "Download failed";
            }
        }

        protected void continueButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/MasterPages/MainPage.aspx");
        }

        public void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            downloadLabel.Visible = false;
            downloadButton.Visible = false;
            downloadMessageLabel.Text = "Download completed! Get the file in your Documents folder";
            continueButton.Visible = true;
        }
    }
}
